package com.cn.shuangzi.ad.custom;

import android.content.Context;
import android.os.SystemClock;
import android.view.ViewGroup;

import com.bytedance.msdk.api.v2.GMAdConstant;
import com.bytedance.msdk.api.v2.ad.custom.GMCustomAdError;
import com.bytedance.msdk.api.v2.ad.custom.bean.GMCustomServiceConfig;
import com.bytedance.msdk.api.v2.ad.custom.splash.GMCustomSplashAdapter;
import com.bytedance.msdk.api.v2.slot.GMAdSlotSplash;
import com.cn.shuangzi.ad.ADManager;
import com.cn.shuangzi.ad.bean.YlhErrorInfo;
import com.cn.shuangzi.ad.util.ADConst;
import com.cn.shuangzi.ad.util.ThreadUtils;
import com.cn.shuangzi.util.SZUtil;
import com.qq.e.ads.splash.SplashAD;
import com.qq.e.ads.splash.SplashADListener;
import com.qq.e.comm.constants.BiddingLossReason;
import com.qq.e.comm.util.AdError;

import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

/**
 * YLH 开屏广告自定义Adapter
 */
public class YlhCustomerSplash extends GMCustomSplashAdapter {

    private volatile SplashAD mSplashAD;
    private boolean isLoadSuccess;

    private int price;
    @Override
    public void load(final Context context, GMAdSlotSplash adSlot, final GMCustomServiceConfig serviceConfig) {
        /**
         * 在子线程中进行广告加载
         */
        ThreadUtils.runOnThreadPool(new Runnable() {
            @Override
            public void run() {
                mSplashAD = new SplashAD(context, serviceConfig.getADNNetworkSlotId(), new SplashADListener() {
                    @Override
                    public void onADDismissed() {
                        SZUtil.logError("优量汇开屏onADDismissed");
                        callSplashAdDismiss();
                    }

                    @Override
                    public void onNoAD(AdError adError) {
                        isLoadSuccess = false;

                        YlhErrorInfo ylhErrorInfo;
                        if (adError != null) {
                            ylhErrorInfo = new YlhErrorInfo(BiddingLossReason.NO_AD);
                            SZUtil.logError("优量汇开屏加载失败-Splash onNoAD errorCode = " + adError.getErrorCode() + " errorMessage = " + adError.getErrorMsg());
                            callLoadFail(new GMCustomAdError(adError.getErrorCode(), adError.getErrorMsg()));
                        } else {
                            SZUtil.logError("优量汇开屏加载失败-无错误信息");
                            ylhErrorInfo = new YlhErrorInfo(BiddingLossReason.NO_AD);
                            callLoadFail(new GMCustomAdError(ADConst.LOAD_ERROR, "no ad"));
                        }
                        ADManager.getInstance().setSplashErrorInfo(ylhErrorInfo);
                    }

                    @Override
                    public void onADPresent() {
                        SZUtil.logError("优量汇开屏onADPresent");
                    }

                    @Override
                    public void onADClicked() {
                        SZUtil.logError("优量汇开屏onADClicked");
                        callSplashAdClicked();
                    }

                    @Override
                    public void onADTick(long l) {
                    }

                    @Override
                    public void onADExposure() {
                        SZUtil.logError("优量汇开屏展示onADExposure");
                        callSplashAdShow();
                    }

                    @Override
                    public void onADLoaded(long expireTimestamp) {
                        SZUtil.logError("优量汇开屏加载完成 expireTimestamp："+expireTimestamp);
                        long timeIntervalSec = expireTimestamp - SystemClock.elapsedRealtime();
                        if (timeIntervalSec > 1000) {
                            SZUtil.logError("优量汇开屏有效 isBidding："+isBidding());
                            isLoadSuccess = true;
                            if (isBidding()) {//bidding类型广告
                                double ecpm = mSplashAD.getECPM(); //当无权限调用该接口时，SDK会返回错误码-1
                                SZUtil.logError("优量汇开屏竞价："+ecpm);
                                if (ecpm < 0) {
                                    ecpm = 0;
                                }
                                price = (int) ecpm;
                                ADManager.getInstance().setSplashErrorInfo(new YlhErrorInfo(BiddingLossReason.LOW_PRICE,price));
                                callLoadSuccess(ecpm);  //bidding广告成功回调，回传竞价广告价格
                            } else { //普通类型广告
                                callLoadSuccess();
                            }
                        } else {
                            SZUtil.logError("优量汇开屏失效");
                            isLoadSuccess = false;
                            callLoadFail(new GMCustomAdError(ADConst.LOAD_ERROR, "ad has expired"));
                        }
                    }
                }, 3000);
                mSplashAD.fetchAdOnly();
                ADManager.getInstance().setCurrentSplashAD(mSplashAD);
            }
        });
    }

    @Override
    public void showAd(final ViewGroup container) {
        if (mSplashAD!=null&&price > 0) {
            mSplashAD.sendWinNotification(price);
            SZUtil.logError("=======上报优量汇开屏数据======="+price);
        }
        SZUtil.logError("=======显示优量汇开屏=======");
        /**
         * 先切子线程，再在子线程中切主线程进行广告展示
         */
        ThreadUtils.runOnUIThreadByThreadPool(new Runnable() {
            @Override
            public void run() {
                if (mSplashAD != null && container != null) {
                    container.removeAllViews();
                    mSplashAD.showAd(container);
                }
            }
        });
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        ADManager.getInstance().setCurrentSplashAD(null);
        mSplashAD = null;
    }


    public boolean isReady() {

        /**
         * 在子线程中进行广告是否可用的判断
         */
        Future<Boolean> future = ThreadUtils.runOnThreadPool(new Callable<Boolean>() {
            @Override
            public Boolean call() throws Exception {
                return isLoadSuccess && mSplashAD != null && mSplashAD.isValid();
            }
        });
        try {
            Boolean result = future.get(500, TimeUnit.MILLISECONDS);//设置500毫秒的总超时，避免线程阻塞
            if (result != null && result) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 是否是Bidding广告
     *
     * @return
     */
    public boolean isBidding() {
        return getBiddingType() == GMAdConstant.AD_TYPE_CLIENT_BIDING;
    }
}
